﻿ using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using IDAL;
using MODEL;

namespace DAL
{
    public class DBContextFactory : IDBContextFactory
    {
        #region  创建 EF上下文 对象，在线程中共享 一个 上下文对象  +DbContext GetDbContext()
        public DbContext GetDbContext(string type)
        {
            DbContext DBContext = CallContext.GetData(type) as DbContext;
            if (DBContext == null)
            {
                switch (type)
                {
          
                case "DeliveryPeriodType":DBContext = new ERPSystemEntities();break;
          
                case "Material":DBContext = new ERPSystemEntities();break;
          
                case "MaterialType":DBContext = new ERPSystemEntities();break;
          
                case "PaymentType":DBContext = new ERPSystemEntities();break;
          
                case "Product":DBContext = new ERPSystemEntities();break;
          
                case "ProductInfo":DBContext = new ERPSystemEntities();break;
          
                case "PurchaseMode":DBContext = new ERPSystemEntities();break;
          
                case "PurchaseModeSection":DBContext = new ERPSystemEntities();break;
          
                case "PurchaseType":DBContext = new ERPSystemEntities();break;
          
                case "Supplier":DBContext = new ERPSystemEntities();break;
          
                case "SupplierBankCard":DBContext = new ERPSystemEntities();break;
          
                case "SupplierModeType":DBContext = new ERPSystemEntities();break;
default : DBContext = new ERPSystemEntities(); break;
                }
                DBContext.Configuration.ValidateOnSaveEnabled = false;
                CallContext.SetData(type, DBContext);
            }
            return DBContext;
        } 
        #endregion
    }

    public class DBSessionFactory:IDBSessionFactory
    {
        #region 在线程中 共用一个 DBSession 对象
        /// <summary>
        /// 在线程中 共用一个 DBSession 对象
        /// </summary>
        /// <returns></returns>
        public IDBSession GetDBSession()
        {
            //从当前线程中  获得DBContext    数据仓储对象
            IDBSession DBSession = CallContext.GetData(typeof(DBSessionFactory).Name) as DBSession;
            if (DBSession==null)
            {
                DBSession = new DBSession();
                CallContext.SetData(typeof(DBSessionFactory).Name, DBSession);
            }
            return DBSession;
        }
        #endregion
    }
}